import COS from 'cos-js-sdk-v5'
import { mapGetters } from 'vuex'
import config from '@/utils/config'
export default {
	computed: {
		...mapGetters(['cos_info']),
	},
	data () {
		return {
			percent: 0,//上传进度
			file_url: '',//地址
			first_frame: '',//第一帧
			loading: false,
			bucket: 'short',
			videoAccept: 'video/*',
			duration: 0,//视频时长
			height: 0,
			width: 0
		}
	},
	methods: {
		async toUpload (file, file_list = '') {
			this.loading = true
			if (!this.cos_info) {
				this.$store
					.dispatch('system/cosInfo')
					.then((res) => {
						this.$nextTick(() => {
							this.CosAction(file)
						})
					})
					.catch((res) => {

					})
			} else {
				this.CosAction(file)
			}
		},


		getVideoDuration (file) {
			const url = URL.createObjectURL(file.raw)
			let that = this
			const video = document.createElement('video')
			video.src = url
			video.muted = false
			video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
			video.currentTime = 1 // 第一帧
			video.preload = "metadata";

			// video.load() // fetches metadata

			video.onloadeddata = function () {
				// Revoke when you don't need the url any more to release any reference
				// URL.revokeObjectURL(url)
				that.duration = parseInt(video.duration)
				that.width = video.videoWidth
				that.height = video.videoHeight

				const canvas = document.createElement('canvas')
				canvas.width = that.width
				canvas.height = that.height
				that.$nextTick(() => {
					// 利用canvas对象方法绘图
					canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
					// 转换成base64形式
					const img = canvas.toDataURL("image/jpeg") // 这个就是图片的base64
					// this.coverUrl = img
					const fileBolb = that.convertBase64UrlToBlob(img)
					that.$request.upload("/upload/create", { file: fileBolb, file_type: 'image' }).then((res) => {
						that.first_frame = res[0].full_path
					})
					canvas.remove();
					video.remove();
				})
			}



			// const ctx = canvas.getContext('2d');
			// video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
			// video.currentTime = 1 // 第一帧
			// video.oncanplay = () => {  //视频准备播放
			// 	ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
			// 	const oGrayImg = canvas.toDataURL("image/png");  //获取base64格式的图片
			// 	const fileBolb = this.convertBase64UrlToBlob(oGrayImg) //转换为二进制
			// 	this.$request.upload("/upload/create", { file: fileBolb, file_type: 'image' }).then((res) => {
			// 		this.first_frame = res[0].full_path
			// 	})
			// 	canvas.remove();
			// }
		},
		reShot(video){
			const canvas = document.createElement('canvas')
			canvas.width = this.width
			canvas.height = this.height
			const ctx = canvas.getContext('2d');
			video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
			video.currentTime = 1 // 第一帧
			let that=this
			video.oncanplay = () => {  //视频准备播放
				ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
				const oGrayImg = canvas.toDataURL("image/png");  //获取base64格式的图片
				const fileBolb = that.convertBase64UrlToBlob(oGrayImg) //转换为二进制
				that.$request.upload("/upload/create", { file: fileBolb, file_type: 'image' }).then((res) => {
					that.first_frame = res[0].full_path
					console.log(that.first_frame,'first_frame')
				})
				canvas.remove();
			}
		},
		CosAction (file) {
			this.percent = 0
			if(this.videoAccept != '.apk'){
				this.getVideoDuration(file)
			}
			
			var cos = new COS({
				getAuthorization: (options, callback) => {
					callback({
						TmpSecretId: this.cos_info.credentials.tmpSecretId,
						TmpSecretKey: this.cos_info.credentials.tmpSecretKey,
						XCosSecurityToken: this.cos_info.credentials.sessionToken,
						StartTime: this.cos_info.startTime,
						ExpiredTime: this.cos_info.expiredTime,
						expiration: this.cos_info.expiration,
						requestId: this.cos_info.requestId,
					})
				},
			})
			let key
			if(this.videoAccept == '.apk'){
				let result = process.env.VUE_APP_API_URL.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im);
			
				key = 'app/download/' + result[1] + '/'+ this.form.version_name  +'peixiu.apk'  
			}else{
				key = this.bucket + '/test/' + Date.parse(new Date()) + '.mp4'
			}
				
			cos.putObject(
				{
					Bucket: config.cos.bucket, // 存储桶名称
					Region: config.cos.region, // 存储桶所在地域，必须字段
					Key: key, // 视频名称
					StorageClass: 'STANDARD',
					Body: file.raw, // 上传文件对象
					onHashProgress: (progressData) => {
						// console.log('校验中', JSON.stringify(progressData))
					},
					onProgress: (progressData) => {
						// const percent = parseInt(progressData.percent * 10000) / 100
						// const speed = parseInt((progressData.speed / 1024 / 1024) * 100) / 100
						// console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;')
						this.percent = parseInt(progressData.percent * 10000) / 100
					},
				},
				(err, data) => {
					if (err) {
						this.$message({ message: '视频文件上传失败,请重新上传', type: 'error' })
					} else {
						this.file_url = config.cos.path + key
						this.loading = false
						console.log('this.file_url上传成功',this.file_url)
						if(this.videoAccept == '.apk'){
							this.form.download_url = this.file_url
							this.$message({ message: '上传成功', type: 'message' })
						}
						// this.$nextTick(() => {
						// 	if(this.videoAccept != '.apk'){
						// 		this.clickScreenshot()
						// 	}
						// })

					}
				}
			)
		},
		clickScreenshot () {
			let video = this.$refs.video
			const canvas = document.createElement('canvas')
			canvas.width = this.width
			canvas.height = this.height
			const ctx = canvas.getContext('2d');
			video.crossOrigin = 'anonymous' // 解决跨域问题，也就是提示污染资源无法转换视频
			video.currentTime = 1 // 第一帧
			video.oncanplay = () => {  //视频准备播放
				ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
				const oGrayImg = canvas.toDataURL("image/png");  //获取base64格式的图片
				const fileBolb = this.convertBase64UrlToBlob(oGrayImg) //转换为二进制
				this.$request.upload("/upload/create", { file: fileBolb, file_type: 'image' }).then((res) => {
					this.first_frame = res[0].full_path
				})
				canvas.remove();
			}
		},
		convertBase64UrlToBlob (urlData) {
			var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new Blob([u8arr], { type: mime });
		}
	},
}